package OperationSystem.day1204_Thread_Pool;

import com.sun.corba.se.spi.orbutil.threadpool.WorkQueue;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

public class MyThreadPool {
    private int nThreads;   //记录允许创建的最多线程数
    private List<Thread> threads;   //工作线程
    private BlockingQueue<Runnable> workQueue;  //任务阻塞队列

    private static class Worker extends Thread {//Worker可以理解为员工
        private BlockingQueue<Runnable> workQueue;

       Worker(BlockingQueue<Runnable> workQueue){//Worker的构造方法
           this.workQueue=workQueue;//需要传入一个阻塞队列
       }

        @Override
        public void run() {
            try {
                while (true) {
                    Runnable target = workQueue.take();//可以理解为消费者
                    target.run();
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }

    MyThreadPool(int nThreads) {    //线程池的构造方法
        this.nThreads = nThreads;

        //创建阻塞队列
        workQueue = new LinkedBlockingDeque<>();//所有线程共享一个阻塞队列对象

        //提交创建的线程
        threads = new ArrayList<>();
        for (int i = 0; i < nThreads; i++) {
            Thread thread = new Worker(workQueue);//向上转型，workQueue是target
            thread.start();
            threads.add(thread);
        }

    }

    void execute(Runnable target) throws InterruptedException {//可以理解为生产者
        workQueue.put(target);
    }
}

